//
//  AppDelegate.swift
//  YR 微博
//
//  Created by cyr on 15/10/8.
//  Copyright © 2015年 cyr. All rights reserved.
//

import UIKit
let YRRootViewControllerSwitchNotification = "YRRootViewControllerSwitchNotification"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        // 注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: YRRootViewControllerSwitchNotification, object: nil)
      
        setupAppearance()
        
        // 1.创建 window
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        
        // 2.创建跟控制器
        window?.rootViewController = defaultViewController()
    
        
        // 3.创建子控制器
        
        
        
        // 4.显示 window
        window?.makeKeyAndVisible()
        
        
        return true
    }
    
    /**
    注销通知
    */
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    /**
    返回启动默认的控制器
    */
    private func defaultViewController() -> UIViewController {
        if !YRUserAccount.userLogon {
            return YRMainViewController()
        }
        
        return isNewUpdate() ? YRNewFeatureViewController() : YRWelcomeViewController()
    }
    
    
    
    /**
    切换控制器
    */
    func switchViewController(n:NSNotification) {
        print("切换控制器\(n)")
        
        let mainVC = n.object as! Bool
        
        window?.rootViewController = mainVC ? YRMainViewController():YRWelcomeViewController()
    }
    
    /**
    检查是否有新版本
    */
    private func isNewUpdate() -> Bool {
        // 1.获取当前程序的版本
        let currentVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)!
        
        // 2.获取之前的版本,偏好设置
        let sandboxVersionKey = "sandboxVersionKey"
        let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
        
        // 3.将当前版本保存到偏好设置
        NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: sandboxVersionKey)
        
        // 4.返回比较结果
        return currentVersion > sandboxVersion
    }
    
    private func setupAppearance(){
        
        UITabBar.appearance().tintColor = UIColor.orangeColor()
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        
    }

}

